package de.szut.sudoku.gui.sudokufield;

import java.awt.event.KeyEvent;

import de.szut.sudoku.main.GameController;

/**
 * Listener for the key value input on a sudokubutton
 * 
 * @author dqi12huisinga
 * 
 */
public class KeyInputListener extends SudokuKeyListener {
	private SudokuFieldLabel source;
	private int[] labelPosition;
	private SudokuFieldLabel[][] sudokuLabels;

	public KeyInputListener(SudokuFieldLabel[][] sudokuLabels) {
		this.sudokuLabels = sudokuLabels;
	}

	/**
	 * Gets the position of a label
	 */
	private void getLabelPosition() {
		labelPosition = new int[2];
		int[] currentIndex = { 0, 0 };
		for (SudokuFieldLabel[] currentLabelLine : sudokuLabels) {
			for (SudokuFieldLabel currentLabel : currentLabelLine) {
				if (currentLabel == source) {
					labelPosition[0] = currentIndex[0];
					labelPosition[1] = currentIndex[1];
				}
				currentIndex[0]++;
			}
			currentIndex[0] = 0;
			currentIndex[1]++;
		}
	}

	/**
	 * Calls a keyPressed event should a key get pressed
	 */
	@Override
	public void keyPressed(KeyEvent keyEvent) {
		setKeyEvent(keyEvent);
		source = (SudokuFieldLabel) getKeyEvent().getSource();
		getLabelPosition();
		// sets the value to 0 if the user entered a reset key
		if (isReset()) {
			GameController.getInstance().getGame()
					.changeValue(0, labelPosition[0], labelPosition[1]);
			// sets the respective value if the user entered a number key
		} else if (isNumber()) {
			GameController
					.getInstance()
					.getGame()
					.changeValue(
							Integer.valueOf(Character.toString((keyEvent
									.getKeyChar()))), labelPosition[0],
							labelPosition[1]);
		}

	}
}
